package org.catdroid.bomba.server.servlet;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.catdroid.bomba.server.Constants;
import org.catdroid.bomba.server.GameManager;
import org.catdroid.bomba.server.GameManager.DuplicateIdException;
import org.catdroid.bomba.server.bean.Player;

import com.google.gson.Gson;

@SuppressWarnings("serial")
public class PlayerServlet extends HttpServlet {
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Gson gson=new Gson();
		GameManager gm=new GameManager();
		resp.setContentType("application/json");
		resp.getWriter().println(gson.toJson(gm.getPlayers()));
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		

		String id= req.getParameter("id");
		String name=req.getParameter("name");
		
		Player player=new Player(id,name);
		GameManager gm=new GameManager();
		
		boolean ok=true;
		try {
			gm.addPlayer(player);
		} catch (DuplicateIdException e) {
			ok=false;
		}
		resp.setContentType("application/json");
		if (ok) {
			resp.getWriter().println(Constants.JSON_OK);
		}else{
			resp.getWriter().println(Constants.JSON_KO);
		}
		
	}
}
